<script setup lang="ts">
import {
    NButton,
    NSpace,
    NDataTable,
    NInput,
    type DataTableColumns,
    NPagination,
    NForm,
    NFormItem,
    NModal,
    NSelect,
    useMessage,
    NDatePicker
} from 'naive-ui'
import { h, onMounted, reactive, ref } from 'vue'
import TableView from '@/components/TableView.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination, HttpResponse } from '@/utils/http'
import type { InterpreterModel } from '@/api/interpreter'
import { useRouter, useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import dayjs from 'dayjs'

const message = useMessage()
const router = useRouter()
const route = useRoute()

onMounted(() => {
    const { interpreterName } = route.query
    if(interpreterName && interpreterName !== '') {
        paginationReactive.nameOrPhone = (interpreterName as any)
    }
    queryTableData(true)
})

const attendOptions = [
    { value: -1, label: '全部' },
    { value: 0, label: '未签到' },
    { value: 1, label: '已签到' },
]

const paginationReactive = reactive({
    nameOrPhone: null,
    date: null,
    teamName: null,
    attendFlag: null,
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [10, 20, 50, 100, 500],
    itemCount: 0,
    onChange: (page: number) => {
        paginationReactive.page = page
        queryTableData()
    },
    onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
        queryTableData()
    }
})

const tableData = ref<InterpreterModel[]>([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
    if (flush) paginationReactive.page = 1
    try {
        tableLoading.value = true
        const [error, res] = await sendRequest<HttpResponsePagination<InterpreterModel>>({
            module: 'interpreter',
            api: 'interpreterSchedulingList',
            override: {
                params: {
                    limit: paginationReactive.pageSize,
                    page: paginationReactive.page,
                    attendFlag: (paginationReactive.attendFlag === -1) ? null : paginationReactive.attendFlag,
                    startWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD') : null,
                    endWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD') : null,
                    nameOrPhone: paginationReactive.nameOrPhone,
                    teamName: paginationReactive.teamName,
                }
            }
        })
        if (error) throw error
        if (res.code !== 0) throw new Error(res.msg)
        tableData.value = res.data.list
        paginationReactive.itemCount = res.data.totalCount
    } catch (error) {
        console.log(error)
    } finally {
        tableLoading.value = false
    }
}
const exportData = async () => {
    const [error, res, headers] = await sendRequest<HttpResponse>({
        module: 'interpreter',
        api: 'interpreterSchedulingExport',
        override: {
            data: {
                limit: paginationReactive.pageSize,
                page: paginationReactive.page,
                attendFlag: (paginationReactive.attendFlag === -1) ? null : paginationReactive.attendFlag,
                startWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD') : null,
                endWrokTime: paginationReactive.date ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD') : null,
                nameOrPhone: paginationReactive.nameOrPhone,
                teamName: paginationReactive.teamName,
            }
        }
    })
    if (error) return message.error(error.message)
    download(headers, res, '考勤记录')
    message.success('导出成功')
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
const columns: DataTableColumns<InterpreterModel> = [
    {
        title: '讲解员姓名',
        key: 'interpreterName',
        align: 'center'
    },
    {
        title: '讲解员手机号',
        key: 'phoneNumber',
        align: 'center'
    },
    {
        title: '访问日期',
        key: 'accessDate',
        align: 'center'
    },
    {
        title: '访问时间',
        key: 'accessTime',
        align: 'center'
    },
    {
        title: '团队名称',
        key: 'teamName',
        align: 'center'
    },
    {
        title: '申请时间',
        key: 'createTime',
        align: 'center'
    },
    {
        title: '是否到场',
        key: 'attendFlag',
        align: 'center',
        render: (row: any, index) => {
            if (row.attendFlag) return '是'
            return '否'
        }
    }
]

</script>

<template>
    <div class="interpreter_record_container">
        <div class="interpreter_record_form">
            <NForm ref="formRef" inline label-placement="left" :model="paginationReactive">
                <NFormItem label="姓名或者手机号：" path="nameOrPhone">
                    <NInput v-model:value="paginationReactive.nameOrPhone" placeholder="请输入姓名或者手机号" clearable />
                </NFormItem>
                <NFormItem label="日期：" path="date">
                    <NDatePicker v-model:value="paginationReactive.date" type="daterange" clearable />
                </NFormItem>
                <NFormItem label="团队名称：" path="teamName">
                    <NInput v-model:value="paginationReactive.teamName" placeholder="请输入团队名称" clearable />
                </NFormItem>
                <NFormItem label="是否到场：" path="status">
                    <NSelect style="width: 150px;" v-model:value="paginationReactive.attendFlag"
                        :options="attendOptions" placeholder="请选择是否到场" clearable />
                </NFormItem>
                <NFormItem>
                    <NButton style="margin-right: 10px;" type="primary" @click="queryTableData(false)">
                        查找
                    </NButton>
                    <NButton type="primary" @click="exportData">
                        导出
                    </NButton>
                </NFormItem>
            </NForm>
        </div>
        <div class="interpreter_record_table">
            <NDataTable :columns="columns" :data="tableData" :pagination="false" :bordered="false" flex-height
                style="height: 100%;" />
        </div>
        <div class="interpreter_record_pagination">
            <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
                :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
                :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
                @update:page-size="paginationReactive.onUpdatePageSize">
                <template #suffix>页</template>
                <template #prefix>
                    <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
                </template>
            </NPagination>
        </div>
    </div>
</template>

<style scoped lang="scss">
.interpreter_record_container {
    height: 100%;
    padding: 30rem;

    .interpreter_record_form {
        height: 7%;
    }

    .interpreter_record_table {
        height: 87%;
    }

    .interpreter_record_pagination {
        height: 6%;
    }
}
</style>
